In this notebook, a template is provided for you to implement your functionality in stages, which is required to successfully complete this project. If additional code is required that cannot be included in the notebook, be sure that the Python code is successfully imported and included in your submission if necessary.
Note: Once you have completed all of the code implementations, you need to finalize your work by exporting the iPython Notebook as an HTML document. Before exporting the notebook to html, all of the code cells need to have been run so that reviewers can see the final implementation and output. You can then export the notebook by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
In addition to implementing code, there is a writeup to complete. The writeup should be completed in a separate file, which can be either a markdown file or a pdf document. There is a write up template that can be used to guide the writing process. Completing the code template and writeup template will cover all of the rubric points for this project.
The rubric contains "Stand Out Suggestions" for enhancing the project beyond the minimum requirements. The stand out suggestions are optional. If you decide to pursue the "stand out suggestions", you can include the code in this Ipython notebook and also discuss the results in the writeup file.
Note: Code and Markdown cells can be executed using the Shift + Enter keyboard shortcut. In addition, Markdown cells can be edited by typically double-clicking the cell to enter edit mode.
# Load pickled data
import pickle
# data provided by Udacity
training_file = './data/train.p'
validation_file= './data/valid.p'
testing_file = './data/test.p'
with open(training_file, mode='rb') as f:
train = pickle.load(f)
with open(validation_file, mode='rb') as f:
valid = pickle.load(f)
with open(testing_file, mode='rb') as f:
test = pickle.load(f)
X_train, y_train = train['features'], train['labels']
X_valid, y_valid = valid['features'], valid['labels']
X_test, y_test = test['features'], test['labels']
The pickled data is a dictionary with 4 key/value pairs:
'features' is a 4D array containing raw pixel data of the traffic sign images, (num examples, width, height, channels).'labels' is a 1D array containing the label/class id of the traffic sign. The file signnames.csv contains id -> name mappings for each id.'sizes' is a list containing tuples, (width, height) representing the original width and height the image.'coords' is a list containing tuples, (x1, y1, x2, y2) representing coordinates of a bounding box around the sign in the image. THESE COORDINATES ASSUME THE ORIGINAL IMAGE. THE PICKLED DATA CONTAINS RESIZED VERSIONS (32 by 32) OF THESE IMAGESComplete the basic data summary below. Use python, numpy and/or pandas methods to calculate the data summary rather than hard coding the results. For example, the pandas shape method might be useful for calculating some of the summary results.
### Replace each question mark with the appropriate value.
### Use python, pandas or numpy methods rather than hard coding the results
# TODO: Number of training examples
n_train = X_train.shape[0]
# TODO: Number of validation examples
n_validation = X_valid.shape[0]
# TODO: Number of testing examples.
n_test = X_test.shape[0]
# TODO: What's the shape of an traffic sign image?
image_shape = X_test.shape[1:]
# TODO: How many unique classes/labels there are in the dataset.
import numpy as np
labels = np.unique(np.concatenate((y_train, y_valid, y_test)))
n_classes = labels.shape[0]
print("Number of training examples =", n_train)
print("Number of validation examples =", n_validation)
print("Number of testing examples =", n_test)
print("Total number of examples =", n_train + n_validation + n_test)
print("Image data shape =", image_shape)
print("Number of classes =", n_classes)
# Display sign ids with their names
import pandas as pd
sign_names_df = pd.read_csv('./signnames.csv', index_col = 'ClassId')
sign_names_df
# Explore train dataset: display class ids
train_df = pd.DataFrame(data = y_train, columns = ['class'])
train_df = pd.merge(train_df, sign_names_df, left_on='class', right_on='ClassId')
train_df
# Explore train dataset: class distribution
train_stats = train_df[['class', 'SignName']].groupby(['class', 'SignName']).size().reset_index(name='counts').sort_values(['counts'])
train_stats
train_stats.plot.bar(x='SignName', y='counts', figsize=(16,9), legend=False)
# Balance classes - calculate class weights for futher use in model training
from sklearn.utils import class_weight
class_weights = class_weight.compute_class_weight('balanced',
np.unique(y_train),
y_train)
class_weights
# Explore validation dataset
valid_df = pd.DataFrame(data = y_valid, columns = ['class'])
valid_df = pd.merge(valid_df, sign_names_df, left_on='class', right_on='ClassId')
valid_stats = valid_df[['class', 'SignName']].groupby(['class', 'SignName']).size().reset_index(name='counts').sort_values(['counts'])
valid_stats.plot.bar(x='SignName', y='counts', figsize=(16,9), legend=False)
# Explore test dataset
test_df = pd.DataFrame(data = y_test, columns = ['class'])
test_df = pd.merge(test_df, sign_names_df, left_on='class', right_on='ClassId')
test_stats = test_df[['class', 'SignName']].groupby(['class', 'SignName']).size().reset_index(name='counts').sort_values(['counts'])
test_stats.plot.bar(x='SignName', y='counts', figsize=(16,9), legend=False)
Visualize the German Traffic Signs Dataset using the pickled file(s). This is open ended, suggestions include: plotting traffic sign images, plotting the count of each sign, etc.
The Matplotlib examples and gallery pages are a great resource for doing visualizations in Python.
NOTE: It's recommended you start with something simple first. If you wish to do more, come back to it after you've completed the rest of the sections. It can be interesting to look at the distribution of classes in the training, validation and test set. Is the distribution the same? Are there more examples of some classes than others?
# Explore training dataset
import matplotlib.pyplot as plt
%matplotlib inline
import cv2
import math
from matplotlib import gridspec
cols = 4
rows = math.ceil(n_classes / cols)
fig = plt.figure(figsize=(16, 40))
gs = gridspec.GridSpec(rows, cols, width_ratios=[1, 1, 1, 1], wspace=0.0, hspace=1.0, top=0.95, bottom=0.05, left=0.17, right=0.845)
i = 1
for label in labels:
for j in range(y_train.shape[0]):
if y_train[j] == label:
subplot = fig.add_subplot(rows, cols, i)
subplot.set_xticklabels([])
subplot.set_yticklabels([])
label_name = sign_names_df.iloc[label]['SignName']
subplot.set_title("#{} {} {}".format(i, label_name, j))
img = X_train[j]
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
plt.imshow(img)
i += 1
break
plt.show()
# Explore test dataset
cols = 4
rows = math.ceil(n_classes / cols)
fig = plt.figure(figsize=(16, 40))
gs = gridspec.GridSpec(rows, cols, width_ratios=[1, 1, 1, 1], wspace=0.0, hspace=1.0, top=0.95, bottom=0.05, left=0.17, right=0.845)
i = 1
for label in labels:
for j in range(y_test.shape[0]):
if y_test[j] == label:
subplot = fig.add_subplot(rows, cols, i)
subplot.set_xticklabels([])
subplot.set_yticklabels([])
label_name = sign_names_df.iloc[label]['SignName']
subplot.set_title("#{} {} {}".format(i, label_name, j))
img = X_test[j]
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
plt.imshow(img)
i += 1
break
plt.show()
# What's inside of 30 km/h of train subset
class_id = 37
images = [x for x, y in zip(X_train, y_train) if y == class_id]
for i, img in enumerate(images[:20]):
plt.figure()
label_name = sign_names_df.iloc[class_id]['SignName']
plt.title("#{} {} {}".format(i+1, label_name, id))
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
plt.imshow(img)
plt.show()
# What's inside of 20 km/h of test subset
class_id = 0
images = [x for x, y in zip(X_test, y_test) if y == class_id]
for i, img in enumerate(images[:20]):
plt.figure()
label_name = sign_names_df.iloc[class_id]['SignName']
plt.title("#{} {} {}".format(i+1, label_name, id))
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
plt.imshow(img)
plt.show()
Design and implement a deep learning model that learns to recognize traffic signs. Train and test your model on the German Traffic Sign Dataset.
The LeNet-5 implementation shown in the classroom at the end of the CNN lesson is a solid starting point. You'll have to change the number of classes and possibly the preprocessing, but aside from that it's plug and play!
With the LeNet-5 solution from the lecture, you should expect a validation set accuracy of about 0.89. To meet specifications, the validation set accuracy will need to be at least 0.93. It is possible to get an even higher accuracy, but 0.93 is the minimum for a successful project submission.
There are various aspects to consider when thinking about this problem:
Here is an example of a published baseline model on this problem. It's not required to be familiar with the approach used in the paper but, it's good practice to try to read papers like these.
Minimally, the image data should be normalized so that the data has mean zero and equal variance. For image data, (pixel - 128)/ 128 is a quick way to approximately normalize the data and can be used in this project.
Other pre-processing steps are optional. You can try different techniques to see if it improves performance.
Use the code cell (or multiple code cells, if necessary) to implement the first step of your project.
### Preprocess the data here. It is required to normalize the data. Other preprocessing steps could include
### converting to grayscale, etc.
### Feel free to use as many code cells as needed.
import cv2
import numpy as np
import tensorflow
# Normalize images
X_train = np.array([cv2.normalize(x, None, 0, 255, cv2.NORM_MINMAX) for x in X_train])
X_valid = np.array([cv2.normalize(x, None, 0, 255, cv2.NORM_MINMAX) for x in X_valid])
X_test = np.array([cv2.normalize(x, None, 0, 255, cv2.NORM_MINMAX) for x in X_test])
# Rescale images to 128x128 for better augmentation (smoother rotation, shadows etc)
original_image_size = 32
image_size = 128
X_train = np.array([cv2.resize(x, (int(image_size),int(image_size))) for x in X_train])
X_test = np.array([cv2.resize(x, (int(image_size),int(image_size))) for x in X_test])
X_valid = np.array([cv2.resize(x, (int(image_size),int(image_size))) for x in X_valid])
# Augment data
from tensorflow.keras.preprocessing.image import ImageDataGenerator
def generate_shadow_coordinates(imshape, figure_count=1):
vertices_list=[]
for index in range(figure_count):
vertex=[]
for dimensions in range(np.random.randint(3,5)):
vertex.append((imshape[1]*np.random.uniform(), imshape[0]//3+imshape[0]*np.random.uniform()))
vertices = np.array([vertex], dtype=np.int32)
vertices_list.append(vertices)
return vertices_list
def add_shadows_and_sunflares(image, shadows_and_sunflares_count=1):
image_HSV = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)
mask = np.zeros(image.shape)
vertices_list = generate_shadow_coordinates(image.shape , shadows_and_sunflares_count)
shadow_intensity = random.uniform(0.7, 1.3) # best 0.7 .. 1.3
for vertices in vertices_list:
cv2.fillPoly(mask, vertices, 1.0)
image_HSV[:,:,2][mask[:,:,0]==1.0] = np.clip(image_HSV[:,:,2][mask[:,:,0]==1.0] * shadow_intensity, 0, 255)
image_RGB = cv2.cvtColor(image_HSV, cv2.COLOR_HSV2RGB)
return image_RGB
import random
def preprocess(img):
shadows_and_sunflares_count = random.randint(0, 2)
return add_shadows_and_sunflares(img, shadows_and_sunflares_count)
# Augment training data: rotate, zoom, shift up/down/left/right, sheer, brighter/darker, add shadows.
# Rescale from 0.255 to 0..1 for DNN model to be more stable
augment_data_generator = ImageDataGenerator(
rotation_range=20,
zoom_range=0.20,
width_shift_range=0.20,
height_shift_range=0.20,
shear_range=0.15,
fill_mode="wrap",
rescale=1.0/255.0,
brightness_range=(0.8, 1.2),
preprocessing_function=preprocess
)
# Rescale validation data from 0.255 to 0..1 for DNN model to be more stable
pass_data_generator = tensorflow.keras.preprocessing.image.ImageDataGenerator(
rescale=1.0/255.0
)
# Obtain one hot encodings for training and validation data
y_train_one_hot = np.array(tensorflow.keras.utils.to_categorical(y_train))
y_valid_one_hot = np.array(tensorflow.keras.utils.to_categorical(y_valid))
# Show augmented training images
n_samples = 10
batch = augment_data_generator.flow(X_train[2100:2120], shuffle=True)[0]
print(batch.shape)
for img in batch:
plt.figure()
plt.imshow(img)
plt.show()
### Define your architecture here.
### Feel free to use as many code cells as needed.
# base_model = tensorflow.keras.applications.vgg16.VGG16(input_shape=(image_size, image_size, 3), include_top=False, weights='imagenet')
# # base_model.layers.pop(4)
# # base_model = tensorflow.keras.applications.xception.Xception(input_shape=(image_size, image_size, 3), include_top=False, weights='imagenet')
# # inp = tensorflow.keras.layers.Input(shape=(image_size, image_size, 3))
# # resize = tensorflow.keras.layers.Lambda(lambda image: tensorflow.image.resize(image, (331, 331)))(inp)
# # base_model = tensorflow.keras.applications.NASNetLarge(input_tensor=inp, include_top=False, weights='imagenet')
# x = base_model.output
# x = tensorflow.keras.layers.Flatten()(x)
# x = tensorflow.keras.layers.Dense(512, activation='relu')(x)
# x = tensorflow.keras.layers.Dropout(0.5)(x)
# x = tensorflow.keras.layers.Dense(512, activation='relu')(x)
# x = tensorflow.keras.layers.Dropout(0.5)(x)
# predictions = tensorflow.keras.layers.Dense(n_classes, activation='softmax')(x)
# model = tensorflow.keras.Model(inputs=base_model.input, outputs=predictions)
# Create VGG-16 model
model = tensorflow.keras.Sequential()
model.add(tensorflow.keras.layers.Conv2D(input_shape=(image_size,image_size,3),filters=64,kernel_size=(3,3),padding="same", activation="relu"))
model.add(tensorflow.keras.layers.Conv2D(filters=64,kernel_size=(3,3),padding="same", activation="relu"))
model.add(tensorflow.keras.layers.MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(tensorflow.keras.layers.Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.Conv2D(filters=128, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(tensorflow.keras.layers.Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.Conv2D(filters=256, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(tensorflow.keras.layers.Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(tensorflow.keras.layers.Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.Conv2D(filters=512, kernel_size=(3,3), padding="same", activation="relu"))
model.add(tensorflow.keras.layers.MaxPool2D(pool_size=(2,2),strides=(2,2)))
model.add(tensorflow.keras.layers.Flatten())
model.add(tensorflow.keras.layers.Dense(512, activation='relu'))
model.add(tensorflow.keras.layers.Dropout(0.5))
model.add(tensorflow.keras.layers.Dense(512, activation='relu'))
model.add(tensorflow.keras.layers.Dropout(0.5))
model.add(tensorflow.keras.layers.Dense(n_classes, activation='softmax'))
from tensorflow.keras.optimizers import RMSprop
model.compile(optimizer=RMSprop(lr=0.00025), loss='categorical_crossentropy', metrics=['accuracy'])
# Show model picture
from tensorflow.keras.utils import plot_model
plot_model(model, show_shapes=True)
A validation set can be used to assess how well the model is performing. A low accuracy on the training and validation sets imply underfitting. A high accuracy on the training set but low accuracy on the validation set implies overfitting.
### Train your model here.
### Calculate and report the accuracy on the training and validation set.
### Once a final model architecture is selected,
### the accuracy on the test set should be calculated and reported as well.
### Feel free to use as many code cells as needed.
BATCH_SIZE = 64
try:
model.load_weights('vgg16_best_weights.hdf5')
except:
history = model.fit(
augment_data_generator.flow(X_train, y_train_one_hot, batch_size=BATCH_SIZE),
steps_per_epoch=math.ceil(len(X_train) / BATCH_SIZE),
epochs=500,
validation_data=pass_data_generator.flow(X_valid, y_valid_one_hot),
verbose = 1,
callbacks=[
tensorflow.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20, verbose=1, min_delta=1e-4, mode='min'),
tensorflow.keras.callbacks.ModelCheckpoint('.mdl_wts.hdf5', save_best_only=True, monitor='val_loss', mode='min'),
tensorflow.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=3, verbose=1, min_delta=1e-4, mode='min')
],
class_weight=class_weights
)
plt.figure()
# list all data in history
print(history.history.keys())
# summarize history for accuracy
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# summarize history for loss
plt.figure()
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'test'], loc='upper left')
plt.show()
# check model accuracy against test data
y_test_one_hot = tensorflow.keras.utils.to_categorical(y_test)
print('\n# Evaluate on test data')
results = model.evaluate(pass_data_generator.flow(X_test, y_test_one_hot))
print('test loss, test acc:', results)
# Plot confusion matrix on test data
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from sklearn import metrics
y_pred = model.predict(pass_data_generator.flow(x=X_test, y=y_test, shuffle=False))
y_pred_label = np.argmax(y_pred, axis=1)
cm = metrics.confusion_matrix(y_test, y_pred_label, normalize='true')
import seaborn as sn
plt.figure(num=None, figsize=(30, 30))
sn.heatmap(cm, annot=True, annot_kws={"size": 8}, xticklabels=sign_names_df[['SignName']].values, yticklabels=sign_names_df[['SignName']].values)
plt.xlabel("Predicted labels")
plt.ylabel("True labels")
plt.title('Confusion matrix ')
plt.show()
# Plot wrong class predictions for test data
y_pred_proba = [value[index] for index, value in zip(y_test, y_pred)]
wrong_prediction_indices = [i for i, v in enumerate(y_pred_label) if y_pred_label[i] != y_test[i]]
for i, wrong_prediction_index in enumerate(wrong_prediction_indices[:500]):
img = X_test[wrong_prediction_index]
plt.figure()
pred_label = y_pred_label[wrong_prediction_index]
pred_label_name = sign_names_df.iloc[pred_label]['SignName']
label = y_test[wrong_prediction_index]
label_name = sign_names_df.iloc[label]['SignName']
plt.title("#{} T: {} / P: {}, {}".format(i+1, label_name, pred_label_name, wrong_prediction_index))
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
plt.imshow(img)
plt.show()
# Check model accuracy against training data
y_train_one_hot = tensorflow.keras.utils.to_categorical(y_train)
print('\n# Evaluate on training data')
results = model.evaluate(pass_data_generator.flow(X_train, y_train_one_hot))
print('train loss, train acc:', results)
To give yourself more insight into how your model is working, download at least five pictures of German traffic signs from the web and use your model to predict the traffic sign type.
You may find signnames.csv useful as it contains mappings from the class id (integer) to the actual sign name.
import os
from glob import iglob
import pathlib
results = iglob(os.path.join('./data/internet/', '*', '*.jpg'))
X_data = []
y_data = []
for file_name in results:
path = pathlib.PurePath(file_name)
y_data.append(int(path.parent.name))
img = cv2.imread(file_name)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
X_data.append(img)
for label, img in zip(y_data, X_data):
plt.figure()
label_name = sign_names_df.iloc[label]['SignName']
plt.title("{}".format(label_name))
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
plt.imshow(img)
plt.show()
### Run the predictions here and use the model to output the prediction for each image.
### Make sure to pre-process the images with the same pre-processing pipeline used earlier.
### Feel free to use as many code cells as needed.
X_data = np.array([cv2.resize(x, (int(image_size),int(image_size))) for x in X_data])
y_data_one_hot = tensorflow.keras.utils.to_categorical(y_data, num_classes=n_classes)
### Calculate the accuracy for these 5 new images.
### For example, if the model predicted 1 out of 5 signs correctly, it's 20% accurate on these new images.
print('\n# Evaluate on test data')
results = model.evaluate(pass_data_generator.flow(X_data, y_data_one_hot))
print('test loss, test acc:', results)
y_data_pred = model.predict(pass_data_generator.flow(x=X_data, y=y_data, shuffle=False))
for img, y_data_true, y_prediction in zip(X_data, y_data, y_data_pred):
y_pred_label = np.argmax(y_prediction)
plt.figure()
pred_label_name = sign_names_df.iloc[y_pred_label]['SignName']
true_label_name = sign_names_df.iloc[y_pred_label]['SignName']
plt.title("True: {} / Pred: {}".format(true_label_name, pred_label_name))
img = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)
plt.imshow(img)
For each of the new images, print out the model's softmax probabilities to show the certainty of the model's predictions (limit the output to the top 5 probabilities for each image). tf.nn.top_k could prove helpful here.
The example below demonstrates how tf.nn.top_k can be used to find the top k predictions for each image.
tf.nn.top_k will return the values and indices (class ids) of the top k predictions. So if k=3, for each sign, it'll return the 3 largest probabilities (out of a possible 43) and the correspoding class ids.
Take this numpy array as an example. The values in the array represent predictions. The array contains softmax probabilities for five candidate images with six possible classes. tf.nn.top_k is used to choose the three classes with the highest probability:
# (5, 6) array
a = np.array([[ 0.24879643, 0.07032244, 0.12641572, 0.34763842, 0.07893497,
0.12789202],
[ 0.28086119, 0.27569815, 0.08594638, 0.0178669 , 0.18063401,
0.15899337],
[ 0.26076848, 0.23664738, 0.08020603, 0.07001922, 0.1134371 ,
0.23892179],
[ 0.11943333, 0.29198961, 0.02605103, 0.26234032, 0.1351348 ,
0.16505091],
[ 0.09561176, 0.34396535, 0.0643941 , 0.16240774, 0.24206137,
0.09155967]])
Running it through sess.run(tf.nn.top_k(tf.constant(a), k=3)) produces:
TopKV2(values=array([[ 0.34763842, 0.24879643, 0.12789202],
[ 0.28086119, 0.27569815, 0.18063401],
[ 0.26076848, 0.23892179, 0.23664738],
[ 0.29198961, 0.26234032, 0.16505091],
[ 0.34396535, 0.24206137, 0.16240774]]), indices=array([[3, 0, 5],
[0, 1, 4],
[0, 5, 1],
[1, 3, 5],
[1, 4, 3]], dtype=int32))
Looking just at the first row we get [ 0.34763842, 0.24879643, 0.12789202], you can confirm these are the 3 largest probabilities in a. You'll also notice [3, 0, 5] are the corresponding indices.
### Print out the top five softmax probabilities for the predictions on the German traffic sign images found on the web.
### Feel free to use as many code cells as needed.
y_data_pred = model.predict(pass_data_generator.flow(x=X_data, y=y_data, shuffle=False))
for i, (img, y_data_true, y_prediction) in enumerate(zip(X_data, y_data, y_data_pred)):
y_pred_labels = np.argsort(y_prediction)[::-1][:5]
print("Image: ", i + 1)
print("Top 5 probabilities: ", y_prediction[y_pred_labels])
print("Top 5 predicted classes: ", y_pred_labels)
print()
Note: Once you have completed all of the code implementations and successfully answered each question above, you may finalize your work by exporting the iPython Notebook as an HTML document. You can do this by using the menu above and navigating to \n", "File -> Download as -> HTML (.html). Include the finished document along with this notebook as your submission.
This Section is not required to complete but acts as an additional excersise for understaning the output of a neural network's weights. While neural networks can be a great learning device they are often referred to as a black box. We can understand what the weights of a neural network look like better by plotting their feature maps. After successfully training your neural network you can see what it's feature maps look like by plotting the output of the network's weight layers in response to a test stimuli image. From these plotted feature maps, it's possible to see what characteristics of an image the network finds interesting. For a sign, maybe the inner network feature maps react with high activation to the sign's boundary outline or to the contrast in the sign's painted symbol.
Provided for you below is the function code that allows you to get the visualization output of any tensorflow weight layer you want. The inputs to the function should be a stimuli image, one used during training or a new one you provided, and then the tensorflow variable name that represents the layer's state during the training process, for instance if you wanted to see what the LeNet lab's feature maps looked like for it's second convolutional layer you could enter conv2 as the tf_activation variable.
For an example of what feature map outputs look like, check out NVIDIA's results in their paper End-to-End Deep Learning for Self-Driving Cars in the section Visualization of internal CNN State. NVIDIA was able to show that their network's inner weights had high activations to road boundary lines by comparing feature maps from an image with a clear path to one without. Try experimenting with a similar test to show that your trained network's weights are looking for interesting features, whether it's looking at differences in feature maps from images with or without a sign, or even what feature maps look like in a trained network vs a completely untrained one on the same sign image.
Your output should look something like this (above)
### Visualize your network's feature maps here.
### Feel free to use as many code cells as needed.
# image_input: the test image being fed into the network to produce the feature maps
# tf_activation: should be a tf variable name used during your training procedure that represents the calculated state of a specific weight layer
# activation_min/max: can be used to view the activation contrast in more detail, by default matplot sets min and max to the actual min and max values of the output
# plt_num: used to plot out multiple different weight feature map sets on the same block, just extend the plt number for each new feature map entry
def outputFeatureMap(image_input, tf_activation, activation_min=-1, activation_max=-1 ,plt_num=1):
# Here make sure to preprocess your image_input in a way your network expects
# with size, normalization, ect if needed
# image_input =
# Note: x should be the same name as your network's tensorflow data placeholder variable
# If you get an error tf_activation is not defined it may be having trouble accessing the variable from inside a function
activation = tf_activation.eval(session=sess,feed_dict={x : image_input})
featuremaps = activation.shape[3]
plt.figure(plt_num, figsize=(15,15))
for featuremap in range(featuremaps):
plt.subplot(6,8, featuremap+1) # sets the number of feature maps to show on each row and column
plt.title('FeatureMap ' + str(featuremap)) # displays the feature map number
if activation_min != -1 & activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin =activation_min, vmax=activation_max, cmap="gray")
elif activation_max != -1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmax=activation_max, cmap="gray")
elif activation_min !=-1:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", vmin=activation_min, cmap="gray")
else:
plt.imshow(activation[0,:,:, featuremap], interpolation="nearest", cmap="gray")
layer_outputs = [layer.output for layer in model.layers]
activation_model = tensorflow.keras.models.Model(inputs=model.input, outputs=layer_outputs)
image_id = 2758
activations = activation_model.predict(np.array([X_test[image_id]]))
images_per_row = 16
for layer, layer_activation in zip(model.layers, activations): # Displays the feature maps
layer_name = layer.name
if isinstance(layer, tensorflow.keras.layers.Conv2D) or isinstance(layer, tensorflow.keras.layers.SeparableConv2D):
n_features = layer_activation.shape[-1] # Number of features in the feature map
size = layer_activation.shape[1] #The feature map has shape (1, size, size, n_features).
n_cols = n_features // images_per_row # Tiles the activation channels in this matrix
display_grid = np.zeros((size * n_cols, images_per_row * size))
for col in range(n_cols): # Tiles each filter into a big horizontal grid
for row in range(images_per_row):
channel_image = layer_activation[0,
:, :,
col * images_per_row + row]
channel_image -= channel_image.mean() # Post-processes the feature to make it visually palatable
channel_image /= channel_image.std()
channel_image *= 64
channel_image += 128
channel_image = np.clip(channel_image, 0, 255).astype('uint8')
display_grid[col * size : (col + 1) * size, # Displays the grid
row * size : (row + 1) * size] = channel_image
scale = 1. / size
plt.figure(figsize=(scale * display_grid.shape[1],
scale * display_grid.shape[0]))
plt.title(layer_name)
plt.grid(False)
plt.imshow(display_grid, aspect='auto', cmap='viridis')